<template>
  <el-dialog :model-value="visible" :title="title" width="80%" @close="handleAddClose">
    <el-form :model="form" ref="formRef" :rules="formRules" label-width="100px">
      <template v-if="form.type == '0'">
        <el-row :gutter="24" style="border: 1px dashed rgb(192, 192, 192); margin: 0 0 20px 0; padding: 0 0 20px 0;">
          <el-col :span="24">
            <h3 style="font-weight: bold;" v-if="form.type == '0'">现场保养</h3>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实施人员" prop="userIdList">
              <SelectionInput v-model="form.userIdList" :form-rules="formRules" :type="'workOrder'" @change="handleSelectionChange" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行位置" prop="execArea">
              <el-input v-model="form.execArea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养内容" prop="bynr">
              <el-input v-model="form.bynr"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业建议" prop="professionalAdvice">
              <el-input type="textarea" v-model="form.professionalAdvice"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养结果" prop="repairResult">
              <el-select v-model="form.repairResult" placeholder="请选择保养结果" required>
                <el-option v-for="item in repairResultList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="form.repairResult=='1'?24:16">
            <el-form-item label="报告照片" prop="picPath">
              <imageUpload v-model="form.picPath" :type="'pic'" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-if="form.type == '1'">
        <el-row v-if="form.id && workorderStatusList" :gutter="24">
          <el-col :span="24">
            <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 10px;">
              <el-step v-for="item in workorderStatusList" :key="item.value" :title="item.label"></el-step>
            </el-steps>
          </el-col>
        </el-row>

        <!-- 现场维修 -->
        <el-row :gutter="24" style="border: 1px dashed rgb(192, 192, 192); margin: 0 0 20px 0; padding: 0 0 20px 0;">
          <el-col :span="24">
            <h3 style="font-weight: bold;" v-if="form.type == '0'">现场保养</h3>
            <h3 style="font-weight: bold;" v-if="form.type == '1'">现场维修</h3>
            <h3 style="font-weight: bold;" v-if="form.type == '2'">现场巡检</h3>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实施人员" prop="userIdList">
              <SelectionInput v-model="form.userIdList" :form-rules="formRules" :type="'workOrder'" @change="handleSelectionChange" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行位置" prop="execArea">
              <el-input v-model="form.execArea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养内容" prop="bynr">
              <el-input v-model="form.bynr"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="问题描述" prop="problemDescription">
              <el-input type="textarea" v-model="form.problemDescription"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="故障原因" prop="reason">
              <el-input v-model="form.reason"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理方法" prop="handMethod">
              <el-input v-model="form.handMethod"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 更换配件 -->
        <el-row :gutter="24" style="border: 1px dashed rgb(192, 192, 192); margin: 0 0 20px 0;">
          <el-col :span="24">
            <h3 style="font-weight: bold;">
              更换配件
              <el-button icon="Plus" @click="addNewAccessory" style="border: none; display: inline-block; color: var(--el-color-success);" />
            </h3>
          </el-col>
          <el-col :span="24" style="padding: 0 30px;">
            <el-col v-for="(item, index) in boList" :key="index" :span="24" style="margin-bottom: 20px; padding-right: 20px; border: 1px dashed #c0c0c0; padding: 20px 0;">
              <el-col :span="24" style="text-align: right; margin-right: 0px;">
                <el-button icon="Minus" @click="removeAccessory(index)" style="border: none; display: inline-block; color: red;" />
              </el-col>
              <AccessoryItem :accessory="item" />
            </el-col>
          </el-col>
          <el-col v-if="boList.length > 0" :span="24" style="text-align: center; padding-bottom: 20px;">
            <el-button type="primary" @click="handleReplaceParts">更换配件保存</el-button>
          </el-col>
        </el-row>

        <!-- 维修结果 -->
        <el-row :gutter="24" style="border: 1px dashed rgb(192, 192, 192); margin: 0 0 20px 0;">
          <el-col :span="24">
            <h3 style="font-weight: bold;" v-if="form.type == '0'">保养结果</h3>
            <h3 style="font-weight: bold;" v-if="form.type == '1'">维修结果</h3>
            <h3 style="font-weight: bold;" v-if="form.type == '2'">巡检结果</h3>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修结果" prop="repairResult">
              <el-select v-model="form.repairResult" placeholder="请选择维修结果" required>
                <el-option v-for="item in repairResultList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.repairResult=='1'" :span="8">
            <el-form-item label="未完成原因" prop="reason">
              <el-select v-model="form.unFinishReason" placeholder="请选择未完成原因" required>
                <el-option v-for="item in reasonList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业建议" prop="professionalAdvice">
              <el-input v-model="form.professionalAdvice"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物业汇报" prop="propertyReport">
              <el-input v-model="form.propertyReport"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="form.repairResult=='1'?24:16">
            <el-form-item label="维修照片" prop="picPath">
              <imageUpload v-model="form.picPath" :type="'pic'" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-if="form.type == '2'">
        <el-row :gutter="24" style="border: 1px dashed rgb(192, 192, 192); margin: 0 0 20px 0; padding: 0 0 20px 0;">
          <el-col :span="24">
            <h3 style="font-weight: bold;" v-if="form.type == '0'">现场巡检</h3>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实施人员" prop="userIdList">
              <SelectionInput v-model="form.userIdList" :form-rules="formRules" :type="'workOrder'" @change="handleSelectionChange" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行位置" prop="execArea">
              <el-input v-model="form.execArea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检内容" prop="bynr">
              <el-input v-model="form.xjnr"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业建议" prop="professionalAdvice">
              <el-input type="textarea" v-model="form.professionalAdvice"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检结果" prop="repairResult">
              <el-select v-model="form.repairResult" placeholder="请选择巡检结果" required>
                <el-option v-for="item in repairResultList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="form.repairResult=='1'?24:16">
            <el-form-item label="巡检照片" prop="picPath">
              <imageUpload v-model="form.picPath" :type="'pic'" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

    </el-form>

    <span slot="footer" class="dialog-footer" style="display: block; text-align: center; margin-top: 20px;">
      <el-button @click="handleAddClose">取消</el-button>
      <el-button type="primary" :loading="buttonLoading" :disabled="replacePartsFlag" @click="onSubmit('temp')">暂存</el-button>
      <el-button type="primary" :loading="buttonLoading" :disabled="replacePartsFlag" @click="onSubmit('submit')">提交/继续</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, watch, reactive } from 'vue';
import SelectionInput from './selectionInput.vue';
import AccessoryItem from './accessoryItem.vue';
import { addWorkorderBatch, tempWorkorSave, submitWorkorderSave } from '@/api/workorder/workorderInfo';

// const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface Accessory {
  model: string;
  count: number;
  isReplaced: boolean;
}

interface RepairResult {
  label: string;
  value: string;
}


export default defineComponent({
  components: {
    SelectionInput,
    AccessoryItem,
  },
  props: {
    visible: Boolean,
    title: String,
    initialData: Object,
    activeStep: Number,
    workorderStatusList: Array,
    workorderId: String,
    workorderPartsList: Array
  },
  emits: ['update:visible', 'close', 'call-parent-method', 'call-parent-page'],
  setup(props, { emit }) {
    const form = reactive({
      id: undefined,
      userIdList: undefined,
      userIds: undefined,
      userNames: undefined,
      execArea: '',
      problemDescription: '',
      reason: '',
      handMethod: '',
      picPath: '',
      repairResult: '',
      professionalAdvice: '',
      propertyReport: '',
      lon: undefined,
      lat: undefined,
      companyName: '',
      companyLogo: '',
      propertyName: '',
      propertyLogo: '',
      sparePartsSource: '',
      unFinishReason: ''
    });

    const formData = reactive({
      userIdArrayList: undefined
    });

    const formRules = {
      execArea: [
        { required: true, message: "执行位置不能为空", trigger: "blur" }
      ],
      problemDescription: [
        { required: true, message: "问题描述不能为空", trigger: "blur" }
      ],
      reason: [
        { required: true, message: "故障原因不能为空", trigger: "blur" }
      ],
      handMethod: [
        { required: true, message: "处理方法不能为空", trigger: "blur" }
      ],
      userIdList: [
        { required: true, message: '请选择相关人员', trigger: ['blur', 'change'] }
      ],
      picPath: [
        { required: true, message: "项目照片不能为空", trigger: "blur" }
      ],
      lon: [
        { required: true, message: "经度不能为空", trigger: "blur" }
      ],
      lat: [
        { required: true, message: "纬度不能为空", trigger: "blur" }
      ],
      companyName: [
        { required: true, message: "企业名称不能为空", trigger: "blur" }
      ],
      companyLogo: [
        { required: true, message: "企业标识不能为空", trigger: "blur" }
      ],
      propertyName: [
        { required: true, message: "物业名称不能为空", trigger: "blur" }
      ],
      propertyLogo: [
        { required: true, message: "物业标识不能为空", trigger: "blur" }
      ],
      repairResult: [
        { required: true, message: "请选择维修结果", trigger: "blur" }
      ],
      professionalAdvice: [
        { required: true, message: "专业建议不能为空", trigger: "blur" }
      ],
      propertyReport: [
        { required: true, message: "物业汇报不能为空", trigger: "blur" }
      ],
      sparePartsSource: [
        { required: true, message: "请选择备件来源", trigger: "blur" }
      ],
      unFinishReason: [
        { required: true, message: "请选择未完成原因", trigger: "blur" }
      ]
    };

    const formRef = ref(null);
    const buttonLoading = ref(false);
    const boList = reactive<Accessory[]>([]);
    const replacePartsFlag = ref(true);
    const repairResultList = readonly(ref<RepairResult[]>([{ label: '完成', value: '0'},{ label: '未完成', value: '1'}]));
    const reasonList = readonly(ref<RepairResult[]>([{ label: '任务升级', value: '0'},{ label: '备件待采', value: '1'}]));
    const sparePartsSourceList = readonly(ref<RepairResult[]>([{ label: '甲供待采', value: '0'},{ label: '备件待采', value: '1'}]));

    const addNewAccessory = () => {
      boList.push({ model: '', count: 0, isReplaced: false });
    };

    const removeAccessory = (index: number) => {
      boList.splice(index, 1);
    };

    const handleReplaceParts = async () => {
      Object.assign(replacePartsFlag.value, false);
      const updatedItems = boList.map(item => ({
        workorderId: props.workorderId, // 添加新的属性
        ...item,
      }));
      const boListRes =  await addWorkorderBatch(updatedItems);
      ElMessage({
        message: boListRes.msg,
        type: boListRes.code=='200'?'success':'warning',
      })
    };

    function handleSelectionChange(userIdList: any[]) {
      // console.log('Selected IDs:', ids);
      form.userIdList = userIdList
      form.userIds = userIdList.map(item => item.userId).join(',');
      form.userNames = userIdList.map(item => item.nickName).join(',');
    }

    function handleAddClose() {
      emit('update:visible', false);
    }

    function onSubmit(type: 'submit' | 'temp') {
      const paramsUrl = type=='temp' ? tempWorkorSave : submitWorkorderSave;
      if (type === 'submit') {
        formRef.value.validate((valid: boolean) => {
          if (valid) {
            form.userIdList = undefined;
            buttonLoading.value = true;
            paramsUrl(JSON.stringify(form)).then(res => {
              if (res.code == '200') {
                ElMessage.success(res.msg);
                handleAddClose();
                emit('call-parent-method');
              } else {
                ElMessage.error(res.msg);
              }
              buttonLoading.value = false;
            }).catch(error => {
              console.error('Error submitting form:', error);
              buttonLoading.value = false;
            });
          } else {
            // console.log('验证失败!!');
            return false;
          }
        });
      } else if (type === 'temp') {
        form.userIdList = undefined;
        buttonLoading.value = true;
        // //如果是完成 将
        // if(form.repairResult == '0'){
        //   form.unFinishReason = null;
        // }
        paramsUrl(JSON.stringify(form)).then(res => {
          if (res.code == '200') {
            ElMessage.success(res.msg);
            handleAddClose();
            emit('call-parent-method');
          } else {
            ElMessage.error(res.msg);
          }
          buttonLoading.value = false;
        }).catch(error => {
          console.error('Error submitting form:', error);
          buttonLoading.value = false;
        });
      }
    }

    // 监听 visible 和 initialData
    watch(
      [() => props.visible, () => props.initialData, () => props.workorderPartsList ],
      ([newVisible, newInitialData, newWorkorderPartsList]) => {
        if (!newVisible) {
          resetForm();
        }
        if (newInitialData) {
          Object.assign(form, newInitialData);
          form.userIdList = newInitialData.userList
        }
        if (newWorkorderPartsList) {
          Object.assign(boList, newWorkorderPartsList);
        } else {
          Object.assign(boList, []);
        }
      }
    );

    function resetForm() {
      Object.keys(form).forEach(key => {
        form[key] = '';
      });
    }

    return {
      form,
      formData,
      formRef,
      formRules,
      handleReplaceParts,
      handleAddClose,
      handleSelectionChange,
      onSubmit,
      boList,
      addNewAccessory,
      removeAccessory,
      repairResultList,
      reasonList,
      sparePartsSourceList
    };
  }
});
</script>
